package com.zyt.wiki.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.zyt.wiki.util.RequestContext;
import com.zyt.wiki.util.SnowFlake;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 【日志输出切面】 使用切面，而不是拦截器，是为了能够输出控制器方法的请求参数
 */
@Aspect
@Component
public class LogAspect {

    public static final Logger LOG = LoggerFactory.getLogger(LogAspect.class) ;

//    @Resource
//    private SnowFlake snowFlake ;

    /** 定义一个切点 */
    @Pointcut("execution(public * com.zyt.*.controller..*Controller.*(..))")
    public void controllerPointcut() {} ;

    @Before("controllerPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        // 增加日志流水号 (并发场景下用于日志跟踪)
//        MDC.put("LOG_ID", String.valueOf(snowFlake.nextId()));

        // 打印请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest() ;
        Signature signature = joinPoint.getSignature() ;

        LOG.info("请求地址: {} {}", request.getRequestURL(), request.getMethod());
        LOG.info("类名方法: {}.{}", signature.getDeclaringTypeName(), signature.getName());
        LOG.info("远程地址: {}", request.getRemoteAddr());

        // 存放客户端IP地址到线程本地存储中
        RequestContext.setRemoteAddr(this.getRemoteIp(request));

        // 打印请求参数
        Object[] args = joinPoint.getArgs();
        Object[] arguments  = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if(args[i] instanceof ServletRequest
                    || args[i] instanceof ServletResponse
                    || args[i] instanceof MultipartFile){
                continue;
            }
            arguments[i] = args[i] ;
        }
        // 排除字段，敏感字段或太长的字段不显示
        String[] excludeProperties = {"password", "file"};
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
        excludefilter.addExcludes(excludeProperties) ;
        LOG.info("请求参数: {}", JSONObject.toJSONString(arguments, excludefilter));
    }

    @Around("controllerPointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis() ;
        Object result = proceedingJoinPoint.proceed() ;
        if(result instanceof byte[]){
            LOG.info("返回结果: 图片流，不输出到日志中") ;
        }else{
            // 排除字段，敏感字段或太长的字段不显示
            String[] excludeProperties = {"password", "file"};
            PropertyPreFilters filters = new PropertyPreFilters();
            PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
            excludefilter.addExcludes(excludeProperties) ;
            LOG.info("返回结果: {}", JSONObject.toJSONString(result, excludefilter));
        }
        LOG.info("------------- 结束 耗时: {} ms -------------", System.currentTimeMillis() - startTime);
        return result ;
    }

    /**
      * 使用nginx做反向代理，需要用该方法才能取到真实的远程IP
      * @param request
      * @return 客户端IP
      */
    public String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
